<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="单位名称" prop="unitName">
            <el-input v-model="queryParams.unitName" placeholder="请输入单位名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
<!--          <el-form-item label="营业执照编码" prop="licenseCode">-->
<!--            <el-input v-model="queryParams.licenseCode" placeholder="请输入营业执照编码" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
          <el-form-item label="集团编码" prop="groupCode">
            <el-input v-model="queryParams.groupCode" placeholder="请输入集团编码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
<!--          <el-form-item label="单位收入归集" prop="unitIncomeCollection">-->
<!--            <el-input v-model="queryParams.unitIncomeCollection" placeholder="请输入单位收入归集" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
          <el-form-item label="使用类型" prop="useType">
            <el-select v-model="queryParams.useType" placeholder="请选择使用类型" clearable>
              <el-option
                v-for="dict in use_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="法人姓名" prop="lpName">
            <el-input v-model="queryParams.lpName" placeholder="请输入法人姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['busi:unitInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['busi:unitInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['busi:unitInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['busi:unitInfo:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="unitInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键id" align="center" prop="id" v-if="false" />
        <el-table-column label="单位名称" align="center" prop="unitName" />
        <el-table-column label="营业执照编码" align="center" prop="licenseCode" />
        <el-table-column label="集团编码" align="center" prop="groupCode" />
        <el-table-column label="单位收入归集" align="center" prop="unitIncomeCollection" />
        <el-table-column label="使用类型" align="center" prop="useType">
          <template #default="scope">
            <dict-tag :options="use_type" :value="scope.row.useType"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="现场核查人员" align="center" prop="verificationStaff" />-->
        <el-table-column label="举报件数" align="center" prop="reportCount" />
        <el-table-column label="法人姓名" align="center" prop="lpName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['busi:unitInfo:edit']"></el-button>
            </el-tooltip>
<!--            <el-tooltip content="新增员工" placement="top">-->
<!--              <el-button link type="primary" icon="Plus" @click="handleAddStaff(scope.row)" v-hasPermi="['busi:unitInfo:add']"></el-button>-->
<!--            </el-tooltip>-->
            <el-tooltip content="查看所有员工" placement="top">
              <el-button link type="primary" icon="View" @click="handleListStaff(scope.row)" v-hasPermi="['busi:unitInfo:list']"></el-button>
            </el-tooltip>
            <el-tooltip content="生成政企文件" placement="top">
              <el-button link type="primary" icon="Download" @click="handleGenUnitDoc(scope.row, 'ZhengQi')" v-hasPermi="['busi:unitInfo:list']"></el-button>
            </el-tooltip>
            <el-tooltip content="生成公众文件" placement="top">
              <el-button link type="primary" icon="Download" @click="handleGenUnitDoc(scope.row, 'GongZhong')" v-hasPermi="['busi:unitInfo:list']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['busi:unitInfo:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改单位基础信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="unitInfoFormRef" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-form-item label="公司照片" prop="companyPhoto">
          <image-upload limit="10" v-model="form.companyPhoto"/>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <template #label>
            营业执照
            <el-button :loading="recognitionLoading" type="primary" icon="Camera" :disabled="!form.businessLicense"  plain @click="handleRecognition" v-hasPermi="['busi:unitInfo:add']">识别</el-button>
            <el-tooltip content="营业之后上传之后，点击识别可自动填充相关信息（注：识别可能有误，请仔细检查）" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <image-upload limit="1" v-model="form.businessLicense"/>
        </el-form-item>
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="单位地址" prop="unitAddress">
            <el-input v-model="form.unitAddress" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="经营范围" prop="businessScope">
            <el-input v-model="form.businessScope" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="营业执照编码" prop="licenseCode">
          <el-input v-model="form.licenseCode" placeholder="请输入营业执照编码" />
        </el-form-item>
        <el-form-item label="行业" prop="industry">
          <el-input v-model="form.industry" placeholder="请输入行业" />
        </el-form-item>
        <el-form-item label="集团编码" prop="groupCode">
          <el-input v-model="form.groupCode" placeholder="请输入集团编码" />
        </el-form-item>
        <el-form-item label="单位收入归集" prop="unitIncomeCollection">
          <el-input v-model="form.unitIncomeCollection" placeholder="请输入单位收入归集" />
        </el-form-item>
        <el-form-item label="工作用途" prop="workPurpose">
            <el-input v-model="form.workPurpose" type="textarea" placeholder="请输入内容" />
        </el-form-item>
<!--        <el-form-item label="外呼时间段" prop="outboundCallTimePeriod">-->
<!--          <el-input v-model="form.outboundCallTimePeriod" placeholder="请输入外呼时间段" />-->
<!--        </el-form-item>-->

        <el-form-item label="外呼时间段" prop="outboundCallTimePeriodArr">
          <el-time-picker
            is-range
            range-separator="-"
            value-format="HH:mm"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            v-model="form.outboundCallTimePeriodArr" placeholder="请输入外呼时间段" />
        </el-form-item>

        <el-form-item label="呼叫频次" prop="callFrequency">
          <el-input-number v-model="form.callFrequency" placeholder="请输入呼叫频次" />
        </el-form-item>
        <el-form-item label="现场核查人员" prop="verificationStaff">
          <el-select v-model="form.verificationStaff"  placeholder="请选择" clearable filterable>
            <el-option
              v-for="item in sysUserList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用类型" prop="useType">
          <el-select v-model="form.useType" placeholder="请选择使用类型">
            <el-option
                v-for="dict in use_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="举报件数" prop="reportCount">
          <el-input-number v-model="form.reportCount" placeholder="请输入举报件数" />
        </el-form-item>
        <el-form-item label="法人身份证正面" prop="lpIdFront">
          <template #label>
            法人身份证正面
            <el-button :loading="idCardFrontLoading" type="primary" icon="Camera" :disabled="!form.lpIdFront"  plain @click="idCardFrontRecognition" v-hasPermi="['busi:unitInfo:add']">识别</el-button>
            <el-tooltip content="身份证正面上传后，点击识别可自动填充相关信息（注：识别可能有误，请仔细检查）" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <image-upload limit="1" v-model="form.lpIdFront"/>
        </el-form-item>
        <el-form-item label="法人身份证反面" prop="lpIdBack">
          <template #label>
            法人身份证反面
            <el-button :loading="idCardBackLoading" type="primary" icon="Camera" :disabled="!form.lpIdBack"  plain @click="idCardBackRecognition" v-hasPermi="['busi:unitInfo:add']">识别</el-button>
            <el-tooltip content="身份证正面上传后，点击识别可自动填充相关信息（注：识别可能有误，请仔细检查）" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <image-upload limit="1" v-model="form.lpIdBack"/>
        </el-form-item>
        <el-form-item label="法人姓名" prop="lpName">
          <el-input v-model="form.lpName" placeholder="请输入法人姓名" />
        </el-form-item>
        <el-form-item label="法人身份证地址" prop="lpIdAddress">
            <el-input v-model="form.lpIdAddress" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="法人证件号码" prop="lpIdNumber">
          <el-input v-model="form.lpIdNumber" placeholder="请输入法人证件号码" />
        </el-form-item>
        <el-form-item label="法人证件有效期" prop="lpIdExpiryArr">
          <el-date-picker
            v-model="form.lpIdExpiryArr"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY.MM.DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="法人联系电话" prop="lpPhone">
          <el-input v-model="form.lpPhone" placeholder="请输入法人联系电话" />
        </el-form-item>
        <el-form-item label="法人邮箱" prop="lpEmail">
          <el-input v-model="form.lpEmail" placeholder="请输入法人邮箱" />
        </el-form-item>
        <el-form-item label="法人性别" prop="lpGender">
          <el-select v-model="form.lpGender" placeholder="请选择法人性别">
            <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 添加或修改员工信息对话框 -->
    <el-dialog :title="staffDialog.title" v-model="staffDialog.visible" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="employeeInfoFormRef" :model="staffForm" :rules="staffRules" label-width="80px" label-position="top">
        <el-form-item label="单位" prop="unitId">
          <el-select v-model="staffForm.unitId" placeholder="请选择" disabled>
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-model="staffForm.employeeName" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="员工身份证地址" prop="employeeIdAddress">
          <el-input v-model="staffForm.employeeIdAddress" placeholder="请输入员工身份证地址" />
        </el-form-item>
        <el-form-item label="员工证件号码" prop="employeeIdNumber">
          <el-input v-model="staffForm.employeeIdNumber" placeholder="请输入员工证件号码" />
        </el-form-item>
        <el-form-item label="员工证件有效期" prop="employeeIdExpiryArr">
          <el-date-picker
            v-model="staffForm.employeeIdExpiryArr"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY.MM.DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="员工联系电话" prop="employeePhone">
          <el-input v-model="staffForm.employeePhone" placeholder="请输入员工联系电话" />
        </el-form-item>
        <el-form-item label="员工邮箱" prop="employeeEmail">
          <el-input v-model="staffForm.employeeEmail" placeholder="请输入员工邮箱" />
        </el-form-item>
        <el-form-item label="员工性别" prop="employeeGender">
          <el-select v-model="staffForm.employeeGender" placeholder="请选择员工性别">
            <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="isOperator" >
          <template #label>
            是否为经办人
            <el-tooltip content="每批次经办人只有一个，选择为 '是' 则会将原来的经办人置为否，会将此人设置为经办人" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-radio-group v-model="staffForm.isOperator">
            <el-radio
              :onchange="changeIsOperator"
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="委托书有效期" prop="authorPeriod" v-if="staffForm.isOperator === 'Y'">
          <el-select v-model="staffForm.authorPeriod" placeholder="请选择委托书有效期">
            <el-option
              v-for="dict in staff_validity_period"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="staffButtonLoading" type="primary" @click="submitStaffForm">确 定</el-button>
          <el-button @click="staffCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 选择白名单批次对话框 -->
    <el-dialog :title="selectBatchDialog.title" v-model="selectBatchDialog.visible" width="500px" append-to-body :close-on-click-modal="false">
      <el-form label-width="80px" ref="selectBatchFormRef" :model="selectBatchForm"  label-position="top">
        <el-form-item label="单位名称" prop="unitId">
          <el-select v-model="selectBatchForm.unitId" placeholder="请选择" disabled>
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="batch">
          <template #label>
            白名单批次
            <el-tooltip content="此批次为白名单批次，为空则默认为最新批次" placement="top">
              <el-icon><question-filled /></el-icon>
            </el-tooltip>
          </template>
          <el-select v-model="selectBatchForm.batch" placeholder="请选择">
            <el-option
              v-for="item in batch"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSelectBatch">确 定</el-button>
          <el-button @click="selectBatchCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UnitInfo" lang="ts">
import {
  listUnitInfo,
  getUnitInfo,
  delUnitInfo,
  addUnitInfo,
  updateUnitInfo,
  queryUnitList,
  genUnitDoc, getBizLicense, getIdCard
} from '@/api/busi/unitInfo';
import {UnitInfoVO, UnitInfoQuery, UnitInfoForm, GenUnitDocQuery} from '@/api/busi/unitInfo/types';
import {EmployeeInfoForm, EmployeeInfoQuery} from "@/api/busi/employeeInfo/types";
import { addEmployeeInfo, updateEmployeeInfo } from '@/api/busi/employeeInfo';
import {UserVO} from "@/api/system/user/types";
import {queryUserList} from "@/api/system/user";
import {tansParams} from "@/utils/ruoyi";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no, batch, sys_user_sex, use_type, staff_validity_period } = toRefs<any>(proxy?.useDict('sys_yes_no', 'batch', 'sys_user_sex', 'use_type', 'staff_validity_period'));

const unitInfoList = ref<UnitInfoVO[]>([]);
const buttonLoading = ref(false);
const recognitionLoading = ref(false);
const idCardFrontLoading = ref(false);
const idCardBackLoading = ref(false);
const staffButtonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const unitList = ref<UnitInfoVO[]>([]);
const sysUserList = ref<UserVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const unitInfoFormRef = ref<ElFormInstance>();
const employeeInfoFormRef = ref<ElFormInstance>();
const selectBatchFormRef = ref<ElFormInstance>();
const defDownType = ref("");

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const staffDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const selectBatchDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const selectPublicBatchDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: UnitInfoForm = {
  id: undefined,
  companyPhoto: undefined,
  businessLicense: undefined,
  unitName: undefined,
  unitAddress: undefined,
  industry: undefined,
  businessScope: undefined,
  licenseCode: undefined,
  groupCode: undefined,
  unitIncomeCollection: undefined,
  workPurpose: undefined,
  outboundCallTimePeriod: undefined,
  callFrequency: undefined,
  useType: undefined,
  verificationStaff: undefined,
  reportCount: undefined,
  lpIdFront: undefined,
  lpIdBack: undefined,
  lpName: undefined,
  lpIdAddress: undefined,
  lpIdNumber: undefined,
  lpIdExpiry: undefined,
  lpPhone: undefined,
  lpEmail: undefined,
  lpGender: undefined,
}

const initStaffFormData: EmployeeInfoForm = {
  id: undefined,
  unitId: undefined,
  employeeName: undefined,
  employeeIdAddress: undefined,
  employeeIdNumber: undefined,
  employeeIdExpiry: undefined,
  employeePhone: undefined,
  employeeEmail: undefined,
  employeeGender: undefined,
  authorPeriod: undefined,
  isOperator: 'N',
}
const initSelectBatchFormData = {
  unitId: undefined,
  batch: undefined
}
const genUnitDocQuery: GenUnitDocQuery = {
  unitId: '',
  batch: ''
}
const data = reactive<PageData<UnitInfoForm, UnitInfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    unitName: undefined,
    licenseCode: undefined,
    groupCode: undefined,
    unitIncomeCollection: undefined,
    useType: undefined,
    verificationStaff: undefined,
    lpName: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键id不能为空", trigger: "blur" }
    ],
    companyPhoto: [
      { required: true, message: "公司照片不能为空", trigger: "blur" }
    ],
    businessLicense: [
      { required: true, message: "营业执照不能为空", trigger: "blur" }
    ],
    unitName: [
      { required: true, message: "单位名称不能为空", trigger: "blur" }
    ],
    unitAddress: [
      { required: true, message: "单位地址不能为空", trigger: "blur" }
    ],
    industry: [
      { required: true, message: "行业不能为空", trigger: "blur" }
    ],
    businessScope: [
      { required: true, message: "经营范围不能为空", trigger: "blur" }
    ],
    licenseCode: [
      { required: true, message: "营业执照编码不能为空", trigger: "blur" }
    ],
    groupCode: [
      { required: true, message: "集团编码不能为空", trigger: "blur" }
    ],
    unitIncomeCollection: [
      { required: true, message: "单位收入归集不能为空", trigger: "blur" }
    ],
    workPurpose: [
      { required: true, message: "工作用途不能为空", trigger: "blur" }
    ],
    outboundCallTimePeriodArr: [
      { required: true, message: "外呼时间段不能为空", trigger: "blur" }
    ],
    callFrequency: [
      { required: true, message: "呼叫频次不能为空", trigger: "blur" }
    ],
    useType: [
      { required: true, message: "使用类型不能为空", trigger: "change" }
    ],
    verificationStaff: [
      { required: true, message: "现场核查人员不能为空", trigger: "change" }
    ],
    reportCount: [
      { required: true, message: "举报件数不能为空", trigger: "blur" }
    ],
    lpIdFront: [
      { required: true, message: "法人身份证正面不能为空", trigger: "blur" }
    ],
    lpIdBack: [
      { required: true, message: "法人身份证反面不能为空", trigger: "blur" }
    ],
    lpName: [
      { required: true, message: "法人姓名不能为空", trigger: "blur" }
    ],
    lpIdAddress: [
      { required: true, message: "法人身份证地址不能为空", trigger: "blur" }
    ],
    lpIdNumber: [
      { required: true, message: "法人证件号码不能为空", trigger: "blur" }, { pattern: /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/, message: "请输入正确的身份证号", trigger: "blur" }
    ],
    lpIdExpiryArr: [
      { required: true, message: "法人证件有效期不能为空", trigger: "blur" }
    ],
    lpPhone: [
      { required: true, message: "法人联系电话不能为空", trigger: "blur" },{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    lpEmail: [
      { required: true, message: "法人邮箱不能为空", trigger: "blur" },{
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"]
      }
    ],
    lpGender: [
      { required: true, message: "法人性别不能为空", trigger: "blur" }
    ],
  }
});

const staffData = reactive<PageData<EmployeeInfoForm, EmployeeInfoQuery>>({
  staffForm: {...initStaffFormData},
  selectBatchForm:{...initSelectBatchFormData},
  staffQueryParams: {
    pageNum: 1,
    pageSize: 10,
    employeeName: undefined,
    employeeIdNumber: undefined,
    employeePhone: undefined,
    params: {
    }
  },
  staffRules: {
    id: [
      { required: true, message: "主键id不能为空", trigger: "blur" }
    ],
    unitId: [
      { required: true, message: "单位id不能为空", trigger: "blur" }
    ],
    employeeName: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" }
    ],
    employeeIdAddress: [
      { required: true, message: "员工身份证地址不能为空", trigger: "blur" }
    ],
    employeeIdNumber: [
      { required: true, message: "员工证件号码不能为空", trigger: "blur" }, { pattern: /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/, message: "请输入正确的身份证号", trigger: "blur" }
    ],
    employeeIdExpiryArr: [
      { required: true, message: "员工证件有效期不能为空", trigger: "blur" }
    ],
    employeePhone: [
      { required: true, message: "员工联系电话不能为空", trigger: "blur" },{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    employeeEmail: [
      { required: true, message: "员工邮箱不能为空", trigger: "blur" },{
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"]
      }
    ],
    employeeGender: [
      { required: true, message: "员工性别不能为空", trigger: "change" }
    ],
    authorPeriod: [
      { required: true, message: "委托书有效期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const {  selectBatchForm, staffForm, staffRules } = toRefs(staffData);

/** 查询单位基础信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUnitInfo(queryParams.value);
  unitInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}
/** 点击下载按钮 */
const handleGenUnitDoc = async (row: UnitInfoVO, type: string) => {
  defDownType.value = type;
  selectBatchReset();
  const units = await queryUnitList();
  unitList.value = units.data;
  selectBatchForm.value.unitId = row.id;
  selectBatchDialog.title = '选择批次';
  selectBatchDialog.visible = true;
}
/** 选择批次后提交 */
const submitSelectBatch = async () => {
  selectBatchFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let downloadLoadingInstance = ElLoading.service({ text: '正在生成数据，请稍后', background: 'rgba(0, 0, 0, 0.7)' })
      genUnitDocQuery.unitId = selectBatchForm.value.unitId;
      genUnitDocQuery.batch = selectBatchForm.value.batch;
      const params = tansParams(genUnitDocQuery);
      let res;
      if (defDownType.value === 'ZhengQi'){
        await proxy?.$download.zip("/busi/unitInfo/genUnitDoc?" + params).finally(() => downloadLoadingInstance.close);
      }else if (defDownType.value === 'GongZhong'){
        await proxy?.$download.zip("/busi/unitInfo/genPublicDoc?" + params).finally(() => downloadLoadingInstance.close);
      }else downloadLoadingInstance.close();
      selectBatchDialog.visible = false;
      await getList();
    }
  });

}
/** 选择批次后取消 */
const selectBatchCancel = async () => {
  selectBatchReset();
  selectBatchDialog.visible = false;

}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}
/** 员工取消按钮 */
const staffCancel = () => {
  resetStaff();
  staffDialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  unitInfoFormRef.value?.resetFields();
}
/** 表单重置 */
const selectBatchReset = () => {
  selectBatchForm.value = {...initSelectBatchFormData};
  selectBatchFormRef.value?.resetFields();
}

/** 员工表单重置 */
const resetStaff = () => {
  staffForm.value = {...initStaffFormData};
  employeeInfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: UnitInfoVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const router = useRouter();

/** 新增按钮操作 */
const handleAdd = async () => {
  // const obj = { path: "unitInfo-add/index" };
  // router.push(obj)
  // router.push("unitInfo-add/index")
  reset();
  dialog.visible = true;
  dialog.title = "添加单位基础信息";
  const users = await queryUserList();
  sysUserList.value = users.data;
}

/** 营业执照识别操作 */
const handleRecognition = async () => {
  await proxy?.$modal.confirm('识别后请检查填充内容是否有误');
  recognitionLoading.value = true;
  // 打开遮罩层
  proxy?.$modal.loading("正在识别，请稍后...");
  const res = await getBizLicense(form.value.businessLicense).finally(() => {recognitionLoading.value = false; proxy?.$modal.closeLoading();})
  for (let key in res.data) {
    if (res.data[key]) {
      form.value[key] = res.data[key]
    }
  }
}

/** 身份证正面识别 */
const idCardFrontRecognition = async () => {
  await proxy?.$modal.confirm('识别后请检查填充内容是否有误');
  idCardFrontLoading.value = true;
  // 打开遮罩层
  proxy?.$modal.loading("正在识别，请稍后...");
  const res = await getIdCard(form.value.lpIdFront).finally(() => {idCardFrontLoading.value = false; proxy?.$modal.closeLoading();})
  for (let key in res.data) {
    if (res.data[key]) {
      form.value[key] = res.data[key]
    }
  }
}
/** 身份证反面识别 */
const idCardBackRecognition = async () => {
  await proxy?.$modal.confirm('识别后请检查填充内容是否有误');
  idCardBackLoading.value = true;
  // 打开遮罩层
  proxy?.$modal.loading("正在识别，请稍后...");
  const res = await getIdCard(form.value.lpIdBack).finally(() => {idCardBackLoading.value = false; proxy?.$modal.closeLoading();})
  for (let key in res.data) {
    if (res.data[key]) {
      form.value[key] = res.data[key]
    }
  }
  form.value.lpIdExpiryArr = res.data.lpIdExpiry.split('-');

}

/** 查看单位下员工 */
const handleListStaff = (row?: UnitInfoVO) => {
  const obj = { path: "employeeInfo/list/index/" + row?.id };
  router.push(obj)
  // router.push("unitInfo-add/index")
}

/** 查询员工信息列表 */
const changeIsOperator = () => {
  staffForm.value.authorPeriod = undefined;
  // isOperator.value = form.value.isOperator === "Y"? "Y" : "N";
}

/** 新增员工按钮 */
const handleAddStaff = async (row?: UnitInfoVO) => {
  resetStaff();
  staffForm.value.unitId = row?.id;
  staffDialog.visible = true;
  staffDialog.title = row?.unitName + "新增员工";
  const units = await queryUnitList();
  unitList.value = units.data;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: UnitInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getUnitInfo(_id);
  Object.assign(form.value, res.data);
  // 将时间段转为array
  form.value.outboundCallTimePeriodArr = res.data.outboundCallTimePeriod.split('-');
  form.value.lpIdExpiryArr = res.data.lpIdExpiry.split('-');
  dialog.visible = true;
  dialog.title = "修改单位基础信息";
  const users = await queryUserList();
  sysUserList.value = users.data;
}

/** 提交按钮 */
const submitForm = () => {
  unitInfoFormRef.value?.validate(async (valid: boolean) => {
    console.log(form.value)
    if (valid) {
      // 将array转为string
      form.value.outboundCallTimePeriod = form.value.outboundCallTimePeriodArr.join('-');
      form.value.lpIdExpiry = form.value.lpIdExpiryArr.join('-')
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUnitInfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addUnitInfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}
/** 提交按钮 */
const submitStaffForm = () => {
  employeeInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 将array转为string
      staffForm.value.employeeIdExpiry = staffForm.value.employeeIdExpiryArr.join('-')
      staffButtonLoading.value = true;
      if (staffForm.value.id) {
        await updateEmployeeInfo(staffForm.value).finally(() =>  staffButtonLoading.value = false);
      } else {
        await addEmployeeInfo(staffForm.value).finally(() =>  staffButtonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      staffDialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: UnitInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除单位基础信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delUnitInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('busi/unitInfo/export', {
    ...queryParams.value
  }, `unitInfo_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
